#include "apue.h"
#include <errno.h>
#include <netdb.h>
#include <syslog.h>

#define BUFSIZE 128

int initserver(int, const struct sockaddr *addr, socklen_t alen, int qlen);

void serve(int sockfd) {
    char buf[BUFSIZE];
    int clfd; 
    FILE *fp;

    while (1) {
        if ((clfd= accept(sockfd, NULL, NULL)) < 0) {
            syslog(LOG_ERR, "pscount: accept error: %s", strerror(errno));
            exit(EXIT_FAILURE);
        }
        set_cloexec(clfd);
        if ((fp= popen("ps -e | wc -l", "r")) < 0) {
            sprintf(buf, "pscount: error: %s", strerror(errno));
            send(clfd, buf, strlen(buf), 0);
        } else {
            while (fgets(buf, BUFSIZE, fp) != NULL)
                send(clfd, buf, strlen(buf), 0);
            pclose(fp);
        }
        close(clfd);
    }
}

int main() {
    struct sockaddr_in addr;
    int sockfd;

    addr.sin_family= AF_INET;
    addr.sin_port= htons(8080);
    addr.sin_addr.s_addr= htonl(INADDR_ANY);

    daemonize("pscout");
    if ((sockfd= initserver(SOCK_STREAM, 
                    (const struct sockaddr*)&addr, sizeof(addr), 0)) < 0)
        err_sys("initserver error");
    serve(sockfd);
    exit(0);
}

